<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/26
 * Time: 15:18
 */

namespace app\model;


use think\facade\Db;
use think\response\Json;
use \Exception as E;

class BoxModel
{
    private static $_baseTable = 'eb_qrcode';
    private static $_orderTable = 'eb_order'; // 订单表
    private static $_schoolTable = 'eb_school'; // 学校表
    private static $_schoolRoleTable = 'eb_school_role'; // 学校管理员表
    private static $_dormitoryTable = 'eb_dormitory'; // 宿舍楼表
    private static $_userTable = 'eb_user'; // 用户表
//    private static $StoreTable = 'eb_store';

    /**查看箱子使用状态
     * @param $input
     * @return Json
     */
    public static function boxStatus($input)
    {
        try {
            $map = [
                ['school_id', '=', $input['school_id']],
                ['code', '=', $input['code']]
            ];
            $data = Db::table(self::$_baseTable)
                ->where($map)
                ->field('code,status')->find();
            if (empty($data)) return jsonFail('暂无数据');
            return jsonSuccess('获取成功', $data);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**修改箱子使用状态
     * @param $input
     * @return Json
     */
    public static function boxUse($input)
    {
        $flag = false;
        try {
            $map[] = ['box_qrcode', '=', $input['code']];
            if ($input['type'] == 1) {
                // 楼栋管理员收货
                $map[] = ['status', '=', 2];
                Db::startTrans();
                $flag = true;
                $rtn = Db::table(self::$_orderTable)->where($map)->update(['status' => 3,'is_arrive' => 1]);
                if (!$rtn) {
                    Db::rollback();
                    return jsonFail('不在配送员接单状态的箱子操作失败');
                }
                $map = [
                    ['code', '=', $input['code']],
                    ['status', '=', 1]
                ];
                $rtn = Db::table(self::$_baseTable)->where($map)->update(['status' => 0]);
                if (!$rtn) {
                    Db::rollback();
                    return jsonFail('配送箱不在使用中操作失败');
                }
                Db::commit();
            } else if ($input['type'] == 2) {
                // 大配送提货
                $rtn = Db::table(self::$_orderTable)->where($map)->update(['is_arrive' => 1]);
                if (!$rtn) {
                    return jsonFail('配送箱已到达无需再次更新');
                }
            } else {
                // 整箱撤回
                $map[] = ['status', '=', 3];
                Db::startTrans();
                $flag = true;
                $rtn = Db::table(self::$_orderTable)->where($map)->update(['status' => 2,'is_arrive' => 0]);
                if (!$rtn) {
                    Db::rollback();
                    return jsonFail('不在配送员送货状态的箱子无法撤回');
                }
                $map = [
                    ['code', '=', $input['code']],
                    ['status', '=', 0]
                ];
                $rtn = Db::table(self::$_baseTable)->where($map)->update(['status' => 1]);
                if (!$rtn) {
                    Db::rollback();
                    return jsonFail('配送箱在使用中无法撤回');
                }
                Db::commit();
            }
            return jsonSuccess('操作成功');
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**修改订单值{装箱员、箱子编号}
     * @param $input
     * @return Json
     */
    public static function boxModify($input)
    {
        $flag = false;
        try {
            $data = json_decode($input['data'], true);
            $orderInfo = [];
            foreach ($data as $key => $value) {
                if (strlen($value['box']) != 20) return jsonFail('请选择箱子码', $value['box']);
                foreach ($value['codes'] as $order) {
                    if (strlen($order) != 22) return jsonFail('订单值值有误，请检查！', $order);
                    $orderInfo[$order] = $value['box'];
                }
            }
            if ($input['type'] == 1) {
                //检测
                $rtn = Db::table(self::$_orderTable)->alias('o')
                    ->leftJoin([self::$_dormitoryTable => 'd'], 'd.id = o.dormitory_id')
                    ->field('o.order_no,d.name as dormitory_name, o.is_pay')
                    ->where('o.order_no', 'in', array_keys($orderInfo))
                    ->select()->toArray();
                return jsonSuccess('获取成功', $rtn);
            } else {
                // 装箱
                $orderNo = array_keys($orderInfo);
                $map = [
                    ['order_no', 'in', $orderNo]
                ];
                $info = Db::table(self::$_orderTable)->alias('o')
                    ->leftJoin([self::$_schoolRoleTable => 'sr'], 'sr.id = o.manag_id')
                    ->where($map)->field('order_no,is_pay,o.status,sr.phone')->select()->toArray();
                if (!$info) return jsonFail('未找到订单信息');
                if (count($info) != count($orderNo)) return jsonFail('有订单不存在，装箱失败');
                $rawSql = "case ";
                foreach ($info as $v) {
                    if ($v['is_pay'] != 1) return jsonFail('该订单未支付不能装箱', [$v['order_no']]);
                    if ($v['status'] != 1) return jsonFail('该订单不是商家接单状态，不能装箱', [$v['order_no']]);
                    $rawSql .= "when order_no='{$v['order_no']}' then {$orderInfo[$v['order_no']]} ";
                }
                $rawSql .= "end";
                Db::startTrans();
                $flag = true;
                // 订单表修改
                $res = Db::table(self::$_orderTable)->where($map)->update([
                    'Boxing_id' => $input['uid'],
                    'status' => 2,
                    'box_qrcode' => Db::raw($rawSql)
                ]);
                if ($res != count($orderNo)) {
                    Db::rollback();
                    return jsonFail('装箱失败');
                }
                // 配送箱表修改
                $boxCode = array_unique($orderInfo);
                $res = Db::table(self::$_baseTable)->where('code', 'in', $boxCode)->update(['status' => 1]);
                if ($res != count($boxCode)) {
                    Db::rollback();
                    return jsonFail('装箱失败');
                }
//                // 发送短信
//                $phone = implode(',', array_unique(array_column($info,'phone')));
//                $code = json_decode(Send_msg('tx',$phone, 'template3'), true);
//                if ($code['code'] != 200) {
//                    Db::rollback();
//                    return jsonFail('装箱失败,发送短信错误', $code);
//                }
                Db::commit();
                return jsonSuccess('装箱成功');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**装箱员查看订单
     * @param $input
     * @return Json
     */
    public static function boxOrderList($input)
    {
        try {
            $map = [
                ['Boxing_id', '=', $input['uid']],
                ['status', '<=', 4]
            ];
            $list = Db::table(self::$_orderTable)
                ->where($map)
                ->field('id,box_qrcode,order_no')->select()->toArray();
            if (empty($list)) return jsonSuccess('获取成功', []);
            $data = self::GetRepeatValGroup($list, 'box_qrcode');
            return jsonSuccess('获取成功', array_values($data));
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**清楚订单装箱信息
     * @param $input
     * @return Json
     */
    public static function boxOrderDel($input)
    {
        try {
            Db::startTrans();
            $res = Db::table('eb_order')->where('order_no', $input['order_no'])->update(['box_qrcode' => '',
                'Boxing_id' => 0,
                'status' => 1,
            ]);
            if ($res != 0) {
                Db::commit();
                return jsonSuccess('清除成功', $res);
            } else {
                Db::rollback();
                return jsonFail('清除失败');
            }
        } catch (E $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**楼栋管理员处----捆绑订单
     * @param $input
     * @return Json
     */
    public static function bindingOrder($input)
    {
        try {
//            $order_nos= explode(',', $input['order_no']);
//            if (empty($order_nos)) return jsonFail('参数格式错误');
            $orders = Db::table('eb_order')->where('order_no', $input['order_no'])->field('manag_id,is_raised,is_arrive')->find();
//            $ids = array_column($orders,'id');
            if (empty($orders)) return jsonFail('暂无订单信息', $input['order_no']);
            if ($orders['manag_id'] != $input['manag_id']) return jsonFail('该订单不属于本楼栋，请核对信息！', $input['order_no']);
            if ($orders['is_raised'] == 2) return jsonFail('该订单属于自提订单', $input['order_no']);
            if ($orders['is_arrive'] == 0) return jsonFail('该订单暂未送达', $input['order_no']);
            Db::startTrans();
            $res = Db::table('eb_order')->where('order_no', $input['order_no'])->update(['status' => 3, 'send_id' => $input['send_id'], 'receipt_time' => time()]);
            if ($res != 0) {
                Db::commit();
                return jsonSuccess('捆绑成功', $res);
            } else {
                Db::rollback();
                return jsonFail('捆绑失败');
            }
        } catch (E $e) {
            Db::rollback();
            return jsonFail($e->getLine());
        }
    }

    /**运营角色查看订单数量
     * @param $input
     * @return Json
     */
    public static function OrderNum($input)
    {
        switch ($input['type']) {
            case 1://1:楼栋管理员 2：装箱员
                $data['count'] = Db::table('eb_order')->where('status', '>=', 4)->where('manag_id', $input['id'])->count();
                $data['list'] = Db::table('eb_order')->where('status', '>=', 4)->where('manag_id', $input['id'])->page($input['page'], $input['limit'])->whereTime('create_time', 'between', [$input['start_time'], $input['end_time']])->field('order_no,status,create_time')->select()->toArray();
                break;
            case 2:
                $data['count'] = Db::table('eb_order')->where('status', '>=', 4)->where('Boxing_id', $input['id'])->count();
                $data['list'] = Db::table('eb_order')->where('status', '>=', 4)->where('Boxing_id', $input['id'])->page($input['page'], $input['limit'])->whereTime('create_time', 'between', [$input['start_time'], $input['end_time']])->field('order_no,status,create_time')->select()->toArray();
                break;
        }
        return jsonSuccess('获取成功', $data);
    }

    /**清楚箱子信息
     * @param $token
     * @return Json
     */
    public static function boxDel($input)
    {
        $flag = false;
        try {
            Db::startTrans();
            $flag = true;
            $map = [
                ['status', '<=', 4],
                ['box_qrcode', '=', $input['code']]
            ];
            $res = Db::table('eb_order')
                ->where($map)->update([
//                'box_qrcode' => '',
//                'Boxing_id' => 0,
                'send_id' => 0,
                'arrive_time' => 0,
                'is_arrive' => 0,
                'status' => 2,
            ]);
            if (!$res) {
                Db::rollback();
                return jsonFail('撤回失败');
            }
            $res = Db::table(self::$_baseTable)->where('code', $input['code'])->update(['status' => 1]);
            if (!$res) {
                Db::rollback();
                return jsonFail('撤回失败');

            }
            Db::commit();
            return jsonSuccess('撤回成功', $res);
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /***骑手扫码获得单
     * @param $input
     * @return Json
     */
    public static function OrderScan($input)
    {
        try {
            $user = Db::table(self::$_userTable)->alias('a')
                ->leftJoin([self::$_schoolTable => 'c'], 'a.school_id=c.id')
                ->leftJoin([self::$_dormitoryTable => 'b'], 'a.dormitory_id=b.id')
                ->where('a.id', $input['send_id'])
                ->field('c.is_go_up,b.manag_id,a.type,a.is_system_order_taking,a.delivery_type,a.dormitory_id')
                ->find();
            if ($user['type'] == 1) return jsonFail('暂时不是配送员，请申请为配送员');
            if ($user['is_system_order_taking'] != 1) return jsonFail('系统禁止接单，请联系管理员');
            if ($user['delivery_type'] == 1) return jsonFail('请主动开启接单模式哟~');
            $orders = Db::table(self::$_orderTable)
                ->where('order_no', $input['order_no'])
                ->field('manag_id,is_raised,is_arrive,dormitory_id,status')
                ->find();
            if (!$orders) return jsonFail('暂无订单信息', $input['order_no']);
            if ($orders['status'] != 3) return jsonFail('您不能接此单', $input['order_no']);
            if ($user['is_go_up'] == 1) {
                if ($orders['manag_id'] != $user['manag_id']) return jsonFail('该订单不属于配送楼栋，请核对信息！', $input['order_no']);
                if ($orders['dormitory_id'] != $user['dormitory_id']) return jsonFail('该订单不属于你配送楼栋，请核对信息！', $input['order_no']);
            }
            if ($orders['is_arrive'] == 0) return jsonFail('该订单暂未送达', $input['order_no']);
            Db::startTrans();
            $res = Db::table('eb_order')
                ->where('order_no', $input['order_no'])
                ->where('status', 3)
                ->update(['status' => 3, 'send_id' => $input['send_id'], 'receipt_time' => time()]);
            if ($res != 0) {
                Db::commit();
                return jsonSuccess('捆绑成功', $res);
            } else {
                Db::rollback();
                return jsonFail('捆绑失败');
            }
        } catch (E $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /***骑手扫码获得单
     * @param $token
     * @return Json
     */
    public static function DormitoryOrder($input)
    {
        $count = Db::table('eb_order')->alias('a')
            ->leftJoin('eb_dormitory b', 'a.dormitory_id=b.id')
            ->where('a.manag_id', $input['manag_id'])
            ->where('a.is_pay', 1)
            ->where('a.status', 2)
            ->where('a.is_arrive', 0)
            ->count();
        $data = Db::table('eb_order')->alias('a')
            ->leftJoin('eb_dormitory b', 'a.dormitory_id=b.id')
            ->where('a.manag_id', $input['manag_id'])
            ->where('a.is_pay', 1)
            ->where('a.is_arrive', 0)
            ->where('a.status', 2)
            ->field('a.order_no,b.name')
            ->select()->toArray();
        return jsonSuccess('获取成功', ['count' => $count, 'data' => $data]);
    }

    /**组合数据，相同的分类为二维，商品为三维
     * @param array $arr
     * @param $keys
     * @return array|bool
     */
    public static function GetRepeatValGroup($arr, $keys)
    {
        if (!is_array($arr) || !$keys) {
            return false;
        }
        $temp = array();
        foreach ($arr as $key => $val) {
            $temp[$val[$keys]]['id'] = $val['id'];
            $temp[$val[$keys]]['box_qrcode'] = $val['box_qrcode'];
            $temp[$val[$keys]]['order'][] = $val;
            foreach ($temp[$val[$keys]]['order'] as &$value) {
                unset($value['id']);
                unset($value['box_qrcode']);
            }
        }
        return $temp;
    }
}